<?php

use Workerman\Worker;
use Workerman\Connection\TcpConnection;

require_once __DIR__.'/../vendor/autoload.php';

$global_uid = 0;

//当客户端连上来时分配uid，并保存连接，并通知所有客户端
function handle_worker_connect($connection){
    global $global_uid;
    $connection->uid = ++$global_uid;
}

//当客户端发来消息转发给其他人
function handle_worker_message($connection, $data){
//    $data = json_decode($data, true);
//    $type = $data['type'];
//    $message = $data['message'];
//    $to_uid = $data['to_uid'];
//    $from_uid = $connection->uid;
//    $connection->send(json_encode(array('type'=>$type, 'message'=>$message, 'from_uid'=>$from_uid)));

    global $worker;

    foreach ($worker->connections as $con){
        $con->send("user[{$connection->uid}] said:$data");
    }
}

// 客户端断开连接
function handle_worker_close($connection){
    global $worker;
    foreach($worker->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] logout");
    }
}


$worker = new Worker('JsonNL://0.0.0.0:1234');

$worker->count = 1;

$worker->onConnect = 'handle_worker_connect';
$worker->onMessage = 'handle_worker_message';
$worker->onClose  = 'handle_worker_close';

Worker::runAll();




